package com.zhenhe.core.common.utils.framework;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.zhenhe.core.common.utils.StringUtils;
import com.zhenhe.core.common.utils.security.MD5;

/**
 * 实名认证类
 * @author hl
 * @date 2016-03-22
 *
 */
public class CertificationUtil {

	public static String SERVER_IP = "180.166.112.24";
	
	public static int SERVER_PORT = 11003;
	
	private static final Logger log = LoggerFactory.getLogger(CertificationUtil.class);
	
	//50个空格
	private static final String FIFTEN_SPACES = "                                                  ";
	
	private static final String SECRET = "UmsLBTY001";
	
	/**
	 * @param cellPhone 手机号
	 * @param idCard 身份证
	 * @param cardNumber 卡号
	 * @param name 姓名
	 * @return
	 */
	public static boolean validate(String cellPhone,String idCard,
			String cardNumber,String name){
		if(StringUtils.anyIsEmpty(idCard,cardNumber,name)){
			log.debug("关键数据为空,cellPhone:{},idCard:{},cardNumber:{},name:{}",cellPhone,idCard,cardNumber,name);
			return false;
		}
		cellPhone = "0";
		//交易码
		StringBuffer sb = new StringBuffer("1100            F00Q                          ");
		
		//时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = sdf.format(new Date());
		sb.append(date);
		
		//手机号
		sb.append(leftFillEmpty(11,cellPhone));
		
		//证件号
		sb.append(leftFillEmpty(32, idCard));
		
		//银行卡号
		sb.append(leftFillEmpty(32, cardNumber));
		
		sb.append(rightFillEmpty(32-name.length(), name));
		
		sb.append(FIFTEN_SPACES);
		
		String Md5Data = MD5.getMD5(sb.toString() + SECRET); 
		System.out.println(sb.toString() + SECRET);
		System.out.println("Md5Data= " + Md5Data);
        log.debug("Md5Data= " + Md5Data);
		
        String reqData = String.format("%04d%s%s",249,sb.toString(),Md5Data);
        log.debug("交易请求数据 = " + reqData);
        System.out.println("交易数据:"+reqData);
        String res = client(reqData);
        System.out.println("收到res,长度:"+res.length());
        System.out.println(res);
        log.debug("recv data ..... :" + res);
        log.debug("SERVER_IP : " + SERVER_IP+","+"SERVER_PORT : " + SERVER_PORT);
        if(StringUtils.contains(res, "验证成功"))
		return true;
        return false;
	}
	
	public static String client(String str)
	{
		Socket socket = null;
		String res = null;
		//SERVER_IP = conjroot.elementText("dzhost");
		//SERVER_PORT = Integer.parseInt(conjroot.elementText("dzport"));
		try {  
            socket = new Socket(SERVER_IP, SERVER_PORT);  
    		InputStream in = socket.getInputStream();
    		OutputStream out = socket.getOutputStream();
    		byte[] sendByte = str.getBytes("GBK");
    		System.out.println(new String(sendByte).length());
    		out.write(sendByte);
    		
    		out.flush();
    		InputStreamReader reader = new InputStreamReader(in, "GBK");//接收字符编码
    		StringBuffer sb = new StringBuffer(1024);
    		char[] buff = new char[1024];
    		int length = 0;
    		while ((length = reader.read(buff)) != -1) {
    			sb.append(buff, 0, length);
    		}
    		out.close();  
            in.close();  
    		res = sb.toString();
        } 
		catch (UnknownHostException e) 
        {  
            log.error("[" + SERVER_IP +" "+ SERVER_PORT+ "] " + e.getMessage() + " <- "
                    + e.getClass().getName());
        } 
		catch (IOException e) 
		{  
			log.error("[client]:in catch IOException.");
        } 
		finally 
		{  
	        if (socket != null) 
	        {  
	            try 
	            {  
	                socket.close();  
	            } 
	            catch (IOException e) { 
	            	log.error("[client]:in catch IOException..");
	            }  
	        }  
        }  
		return res;
	}
	
	private static String leftFillEmpty(int length,String content){
		Assert.notNull(content,"content不能为空");
		StringBuffer sb = new StringBuffer();
		int needSpace = length - content.length();
		for(int i=0;i<needSpace;i++){
			sb.append(" ");
		}
		sb.append(content);
		return sb.toString();
	}
	
	private static String rightFillEmpty(int length,String content){
		Assert.notNull(content,"content不能为空");
		StringBuffer sb = new StringBuffer();
		sb.append(content);
		int needSpace = length - content.length();
		for(int i=0;i<needSpace;i++){
			sb.append(" ");
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		//02490011            F00O                   
		//2016032218483915050464702              
		//320504198902152032               
		//62179208001580072胡良                                                                                
		//41e7fb55afc2cb804b6bbb19b69c2af1
		boolean b = validate("0", "420684199108085069", "6214922000660476", "黄燕");
//	System.out.println("02491100            F00Q                          2016040815080515050464702              320504198902152032               62179208001580072胡良                                                                                3a94ce1cee05fa389c8c3fa816f3506f".length());
		System.out.println(b);
	}

}
